


//插入用户
function insertUser(user){

    var myAuto = document.getElementById('msgMusic');
    myAuto.play();
    var i = app.userIds.indexOf(user['hx_id']);

    var msg_num = 0;
    if(i>=0){
        msg_num = app.userList[i].msg_num;
        app.userList.splice(i,1);
        app.userIds.splice(i,1);
    }

    if(app.onUser.hx_id && app.onUser.hx_id != user['hx_id']){
        user.msg_num = parseInt(msg_num) + 1;
    }else{
        user.msg_num = 0;
    }

    app.userList.unshift(user);
    app.userIds.unshift(user['hx_id']);
}


//插入消息
function insertMsg(type,message){
    var userid = message.ext.hx_id;

    if(app.userMessage[userid]==undefined){
        switch(type){
            case 1:      //文字
                app.userMessage[userid] = [{attr:'other',type:1,text:message.data}];
                break;
            case 2:     //图片
                app.userMessage[userid] = [{attr:'other',type:2,url:message.url}];
                break;
            case 3:     //房源链接
                app.userMessage[userid] = [{
                    attr:'other',
                    type:3,
                    house_address:message.ext.house_address,
                    house_id:message.ext.house_id,
                    house_img:message.ext.house_img,
                    house_intro:message.ext.house_intro,
                    house_title:message.ext.house_title
                 }];

                break;
            case 4:     //语音
                // var audioUrl = 'http://app.5b245.com/backstage/readAudio/?audioUrl='+message.url;
                // var audioUrl = message.url;

                app.userMessage[userid] = [];
                switchAudio(message.url,userid,1);
                // console.log('audiourl',audioUrl);
                //
                // app.userMessage[userid] = [{attr:'other',type:4,url:audioUrl}];
                break;
            case 5:     //位置
                app.userMessage[userid] = [{attr:'other',type:5,addr:message.addr,lng:message.lng,lat:message.lat}];
                break;
        }

    }else{
        switch(type){
            case 1:      //文字
                app.userMessage[userid].push({attr:'other',type:1,text:message.data});

                break;
            case 2:     //图片
                app.userMessage[userid].push({attr:'other',type:2,url:message.url});

                break;
            case 3:     //房源链接
                app.userMessage[userid].push({
                    attr:'other',
                    type:3,
                    house_address:message.ext.house_address,
                    house_id:message.ext.house_id,
                    house_img:message.ext.house_img,
                    house_intro:message.ext.house_intro,
                    house_title:message.ext.house_title
                });

                break;
            case 4:     //音频
                // var audioUrl = 'http://app.5b245.com/backstage/readAudio/?audioUrl'+message.url;
                // var audioUrl = message.url;
                // var audioUrl = switchAudio(message.url);
                switchAudio(message.url,userid,2);

                // console.log('audiourl',audioUrl);

                // app.userMessage[userid].push({attr:'other',type:4,url:audioUrl});

                break;
            case 5:     //位置
                app.userMessage[userid].push({attr:'other',type:5,addr:message.addr,lng:message.lng,lat:message.lat});
                break;
        }
    }

    chatBox();

}

//转换音频
function switchAudio(url,userid,type){
    var options = { url: url };
    // $("#chatbox").hide();

    options.onFileDownloadComplete = function ( response ) {
        //音频下载成功，需要将response转换成blob，使用objectURL作为audio标签的src即可播放。
        var objectURL = WebIM.utils.parseDownloadResponse.call(conn, response);

        // console.log(objectURL);
        // if(type==1){
        //
        //     app.userMessage[userid] = [{attr:'other',type:4,url:objectURL}];
        //     app.userMessage[userid].push({attr:'other',type:4,url:objectURL});
        //
        //     // app.userMessage[userid] = [{attr:'other',type:4,url:objectURL}];
        //     // app.userMessage[userid].push({attr:'other',type:4,url:objectURL});
        //     // $("#chatbox").load();
        //
        // }else{
            app.userMessage[userid].push({attr:'other',type:4,url:objectURL});

        // }
        console.log(app.userMessage,22);

        chatBox();

        return false;

        // return objectURL;
    };

    options.onFileDownloadError = function () {
        //音频下载失败
    };

    //通知服务器将音频转为mp3
    options.headers = {
        'Accept': 'audio/mp3'
    };

    WebIM.utils.download.call(conn, options);
}

//滚动条
function chatBox(){
    setTimeout(function(){
        var chat = $('#chatbox');

        var hideHeight = chat.height() - $('#officeText').height();

        console.log(hideHeight);
        if (hideHeight > 0) {
            //滑动滚动条
            chat.css('top', $('#officeText').height() - parseInt(chat.height() + 15));

        }else{
            chat.css('top',0);

        }
    },200);

}

//隐藏表情弹层
function hideEmoji(){
    $('#tagleIcon').hide();
    $('.biaoqing').hide();
}

//选择表情
function selectedIcon(type,obj){
    if(type==1){
        $('.emojis').show();
        $('.gif-img').hide();

    }else{
        $('.emojis').hide();
        $('.gif-img').show();

    }

    $(obj).addClass('selected').siblings().removeClass('selected');
}

//三图标
window.onload = function () {
    function a() {
        var si1 = document.getElementById('si_1');
        var si2 = document.getElementById('si_2');
        // var si3 = document.getElementById('si_3');
        si1.onclick = function () {
            si1.style.background = "url(/backstage/lib/chat/images/icon/head_2_1.png) no-repeat"
            si2.style.background = "";
            // si3.style.background = "";
        };
        si2.onclick = function () {
            si2.style.background = "url(/backstage/lib/chat/images/icon/head_3_1.png) no-repeat"
            si1.style.background = "";
            // si3.style.background = "";
        };
        // si3.onclick = function () {
        //     si3.style.background = "url(/backstage/lib/chat/images/icon/head_4_1.png) no-repeat"
        //     si1.style.background = "";
        //     si2.style.background = "";
        // };
    };
    function b() {
        var text = document.getElementById('input_box');
        var chat = document.getElementById('chatbox');
        var btn = document.getElementById('send');
        var talk = document.getElementById('talkbox');
        btn.onclick = function () {
            sendMessage()
        };
    };

//            $("#input_box").keydown(function(e) {
//                sendMessage()
//            });
    $('#input_box').on('keypress', function (event) {

        // console.log(keypress);
        if (event.keyCode == 13) {
            event.preventDefault();
//                    event.returnValue = false;
            sendMessage()
        }
    });

    //发送文本消息
    function sendMessage() {
        var text = document.getElementById('input_box');
//            var chat = $('#chatbox');
        var talk = document.getElementById('talkbox');


        // var chatmsg  = app.chatMsg;

        if(!app.onUser){
            return false;
        }

        if ($(text).html() == '') {
//                    alert('不能发送空消息');
            text.placeholder = '不能发送空消息';
        } else {

            sendPrivateText($(text).html(),app.onUser.hx_id);
            text.placeholder = '';
            var nowUser = app.onUser.hx_id;
            var nowMsg = {attr:'me',type:1,text:$(text).html()};
            if(app.userMessage[nowUser]==undefined){

                app.userMessage[nowUser] = [nowMsg];
//                    app.onMessage = [nowMsg];

            }else{
                app.userMessage[nowUser].push(nowMsg);
//                    app.onMessage.push(nowMsg);

            }
            chatBox();

//                chat.html(chat.html() + '<li class="me"><img src="' + '{$imgPath}{$broker["avatar"]}' + '"><span>' + text.value + '</span></li>');
//             text.value = ''; //清空输入框

            $(text).html('');
            // app.chatMsg = '';

            talk.style.background = "#fff";
            text.style.background = "#fff";
        }

    }

    a();
    b();
};

// 单聊发送文本消息
function sendPrivateText(text,username) {

    console.log('text',text);
    text = imgParseEmoji(text);
    // console.log(app.brokerInfo);
    var id = conn.getUniqueId();                 // 生成本地消息id
    var msg = new WebIM.message('txt', id);      // 创建文本消息
    msg.set({
        msg: text,                  // 消息内容
        to: username,                          // 接收消息对象（用户id）
        ext: app.brokerInfo,
        roomType: false,
        success: function (id, serverMsgId) {
            console.log('发送文本成功',id,serverMsgId);
        },
        fail: function(e){
            console.log("发送失败",e);
        }
    });
    msg.body.chatType = 'singleChat';

    conn.send(msg.body);
};


// 单聊发送动态表情
function sendPrivateGif(flag) {

    // console.log(app.brokerInfo);
    var id = conn.getUniqueId();                 // 生成本地消息id
    var msg = new WebIM.message('txt', id);      // 创建文本消息
    var ext = {
        em_expression_id:flag,
        em_is_big_expression:true,
        hx_avatarurlpath:app.brokerInfo.hx_avatarurlpath,
        hx_id:app.brokerInfo.hx_id,
        hx_nickname:app.brokerInfo.hx_nickname
    }

    msg.set({
        msg: '',                  // 消息内容
        to: app.onUser.hx_id,                          // 接收消息对象（用户id）
        ext: ext,
        roomType: false,
        success: function (id, serverMsgId) {
            console.log('发送gif成功',id,serverMsgId);

        },
        fail: function(e){
            console.log("发送失败",e);
        }
    });
    msg.body.chatType = 'singleChat';

    conn.send(msg.body);

    var imgurl = app.emojiPath+'gif/'+flag+'.gif';

    var nowUser = app.onUser.hx_id;
    var nowMsg = {attr:'me',type:2,url:imgurl};
    if(app.userMessage[nowUser]==undefined){

        app.userMessage[nowUser] = [nowMsg];
//                    app.onMessage = [nowMsg];
    }else{
        app.userMessage[nowUser].push(nowMsg);
//                    app.onMessage.push(nowMsg);

    }

    chatBox();



};

// 单聊发送图片消息
function sendPrivateImg(imgurl) {
    var id = conn.getUniqueId();                   // 生成本地消息id
    var msg = new WebIM.message('img', id);        // 创建图片消息
    var input = document.getElementById('msgImg');  // 选择图片的input
    var file = WebIM.utils.getFileUrl(input);      // 将图片转化为二进制文件
    var allowType = {
        'jpg': true,
        'gif': true,
        'png': true,
        'jpeg':true,
        'bmp': true
    };
    if (file.filetype.toLowerCase() in allowType) {
        var option = {
            apiUrl: WebIM.config.apiURL,
            file: file,
            to: app.onUser.hx_id,                       // 接收消息对象
            roomType: false,
            chatType: 'singleChat',
            ext: app.brokerInfo,
            onFileUploadError: function () {      // 消息上传失败
                console.log('图片上传失败');
            },
            onFileUploadComplete: function () {   // 消息上传成功
                console.log('图片上传成功');
            },
            success: function () {                // 消息发送成功
                console.log('sendSuccess');
            },
            flashUpload: WebIM.flashUpload
        };
        msg.set(option);
        conn.send(msg.body);
    }

    var nowUser = app.onUser.hx_id;
    var nowMsg = {attr:'me',type:2,url:imgurl};
    if(app.userMessage[nowUser]==undefined){

        app.userMessage[nowUser] = [nowMsg];
//                    app.onMessage = [nowMsg];

    }else{
        app.userMessage[nowUser].push(nowMsg);
//                    app.onMessage.push(nowMsg);

    }

    chatBox();

};


//接收消息 将emoji符号转换成img标签
function parseEmoji(message){

    // var str = message.data.match(/\[(\S*)\]/);
    var re = /\[(.*?)\]/g;
    // var str = re.exec(message.data);
    // var text = message.data;
    var imgPath = '/backstage/lib/chat/images/';
    while (temp = re.exec(message.data)) {
        // console.log('str',temp);

        if(emoji = emojis[temp[0]]){
            // console.log(temp[0],emoji);
            message.data = message.data.replace(temp[0],'<img style="float:none !important;width:20px !important;height: 20px !important;margin: 0 2px!important;position: relative;bottom:3px;" src="'+imgPath+emoji+'"/>');
            // text = text.replace(temp[0],'emoji');
        }
    }

    return message;
}


//图片转换emoji符号 发送消息
function imgParseEmoji(message){

    // var str = message.data.match(/\[(\S*)\]/);
    var re = /<img(.*?)>/g;
    var msg = message;
    while (temp = re.exec(message)) {
        console.log('img',temp[1]);
        var re2  =  /flag="(.*?)"/g;


        var emoji = re2.exec(temp[1]);
        console.log('flag',emoji[1]);

        //将img标签替换成emoji符号
        msg = msg.replace(temp[0],emoji[1]);

    }

    return msg;
}

var emojis = {
    '[):]': 'ee_1.png',
    '[:D]': 'ee_2.png',
    '[;)]': 'ee_3.png',
    '[:-o]': 'ee_4.png',
    '[:p]': 'ee_5.png',
    '[(H)]': 'ee_6.png',
    '[:@]': 'ee_7.png',
    '[:s]': 'ee_8.png',
    '[:$]': 'ee_9.png',
    '[:(]': 'ee_10.png',
    '[:\'(]': 'ee_11.png',
    '[:|]': 'ee_12.png',
    '[(a)]': 'ee_13.png',
    '[8o|]': 'ee_14.png',
    '[8-|]': 'ee_15.png',
    '[+o(]': 'ee_16.png',
    '[<o)]': 'ee_17.png',
    '[|-)]': 'ee_18.png',
    '[*-)]': 'ee_19.png',
    '[:-#]': 'ee_20.png',
    '[:-*]': 'ee_21.png',
    '[^o)]': 'ee_22.png',
    '[8-)]': 'ee_23.png',
    '[(|)]': 'ee_24.png',
    '[(u)]': 'ee_25.png',
    '[(S)]': 'ee_26.png',
    '[(*)]': 'ee_27.png',
    '[(#)]': 'ee_28.png',
    '[(R)]': 'ee_29.png',
    '[({)]': 'ee_30.png',
    '[(})]': 'ee_31.png',
    '[(k)]': 'ee_32.png',
    '[(F)]': 'ee_33.png',
    '[(W)]': 'ee_34.png',
    '[(D)]': 'ee_35.png'
}